package solver.moves;

import java.awt.Container;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

import model.MachineSelector;
import model.Solution;
import model.SolverEnvironment;

public class EliminateSingleMachineCost extends AbstractComplexMove {
	
	MachineSelector ms;
	
	public EliminateSingleMachineCost(SolverEnvironment env, MachineSelector ms) {
		super(env);
		this.ms = ms;
	}


	@Override
	public boolean performMove() {
		boolean success = false;
		long init_cost=getCc().getNewSolutionCost();
		
		int orig_m1_index = ms.selectMostLoadedMachine(getRandom().nextInt(Math.min(Math.max(getProblem().M/10,1),5))+1);
		Solution pot_sol = env.getPotentialSolution();
		List<Integer> l1 = pot_sol.getProcessesForMachine(orig_m1_index);
		if (l1.size()==0)
			return false;
		Collections.shuffle(l1,getRandom());
		for(Integer p:l1){
			long local_cost=getCc().getNewSolutionCost();
			int m = testSequentiallyBestNoSchedule(p, orig_m1_index, orig_m1_index+1, orig_m1_index+getProblem().M);
			if (m!=-1 && m!=orig_m1_index){
				long new_cost=getCc().getProcessMoveToMachineCost(pot_sol, p, orig_m1_index, m);
				if(local_cost<new_cost){
					makeMove(p, orig_m1_index, m);
					getCc().updateNewSolutionCost();
					success=true;
				}
			}
		}
		getCc().clearDelta();
		return success;
	}

}
